/*
 Copyright (c) 2009, Ivan Popivanov
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

 * Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the
 documentation and/or other materials provided with the distribution.

 * Neither the name of StockCandles nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <math.h>

#include "Csv.h"
#include "Ohlc.h"

bool
Ohlc::fromDaily(const Ohlc &other, const TimeFrame &tf)
{
   resize(other.size());

   int firstIndex = -1;
   for(int i = other.latest(); i > 0; --i)
   {
      // Initialize the summarized candle
      setAt(i, other);

      QDate stopDate;
      if(tf.isWeekly())
      {
         stopDate = other.d[i].addDays(-7*tf.length());
      }
      else if(tf.isMonthly())
      {
         stopDate = other.d[i].addMonths(-tf.length());
      }
      else if(tf.isQuarterly())
      {
         stopDate = other.d[i].addMonths(-3*tf.length());
      }
      else if(tf.isAnnual())
      {
         stopDate = other.d[i].addMonths(-12*tf.length());
      }

      int j;
      for(j=i-1; j >= 0; --j)
      {
         // Check whether we have gone too far
         bool tooFar = false;
         if(tf.isDaily())
         {
            if(tf.length() < (i - j))
            {
               tooFar = true;
            }
         }
         else
         {
            tooFar = stopDate >= other.d[j];
         }

         if(tooFar)
         {
            // Remember the last computed value
            firstIndex = i;

            // Summarize the volume
            int days = i - j;
            if(days > 0)
            {
               v[i] /= days;
            }
            break;
         }

         v[i] += other.v[j];
         h[i] = qMax(h[i], other.h[j]);
         l[i] = qMin(l[i], other.l[j]);
      }

      if(j < 0)
      {
         break;
      }
   }

   if(firstIndex < 0) return false;

   // Shift values leftwards
   for(int i = firstIndex; i < other.size(); ++i)
   {
      setAt(i - firstIndex, d[i], o[i], h[i], l[i], c[i], v[i]);
   }

   // Resize
   resize(size() - firstIndex);

   return true;
}

int
Ohlc::sample(const Ohlc &other, int first, const TimeFrame &tf, int maxCnt)
{
   resize(maxCnt);

   int j = 0;
   int otherId = first;
   int outId = maxCnt - 1;
   while(otherId >= 0 && j < maxCnt)
   {
      setAt(outId, other, otherId);

      otherId = other.periodEnd(first, tf, 1+j);

      ++j;
      --outId;

      if(otherId < 0) break;
   }

   return j;
}

int
Ohlc::periodEnd(int latest, const TimeFrame &period, int times /* = 1 */) const
{
   QDate stopDate;
   int step;

   if(period.isDaily())
   {
      step = period.length()*times;
   }
   else if(period.isWeekly())
   {
      step = 5*period.length()*times;
      stopDate = d[latest].addDays(-7*period.length()*times);
   }
   else if(period.isMonthly())
   {
      step = 24*period.length()*times;
      stopDate = d[latest].addMonths(-period.length()*times);
   }
   else if(period.isQuarterly())
   {
      step = 72*period.length()*times;
      stopDate = d[latest].addMonths(-3*period.length()*times);
   }
   else if(period.isAnnual())
   {
      step = 300*period.length()*times;
      stopDate = d[latest].addYears(-period.length()*times);
   }

   int oldest = latest - step;
   if(oldest < 0) return oldest;

   if(!period.isDaily())
   {
      // We may need to move closer to stopDate in case we skipped
      // days with our initial choice (for example holidays make
      // the weeks shorter)
      while(d[oldest+1] <= stopDate)
      {
         ++oldest;
      }
   }

   return oldest;
}

bool
Ohlc::findHighLow(const QDate &latestDate, const TimeFrame &period, double &hi, double &low)
{
   int i;

   for(i = d.size() - 1; i >= 0; --i)
   {
      if(latestDate >= d[i]) break;
   }

   if(i < 0) return false;

   int j = periodEnd(i, period);
   if(j < 0) return false;

   hi = h[j];
   low = l[j];

   while(j <= i)
   {
      hi = qMax(hi, h[j]);
      low = qMin(low, l[j]);
      ++j;
   }

   return true;
}

void
Ohlc::copy(const Ohlc &o)
{
   resize(o.size());
   for(int i = 0; i < o.size(); ++i)
   {
      setAt(i, o);
   }
}

bool
Ohlc::loadFromYahooCsv(const QString &path, const QDate *start /* = NULL */)
{
   bool result = false;

   reserve(1000);
   resize(0);

   CsvFile file(path);

   if(file.open(QFile::ReadOnly))
   {
      QStringList list;

      // Skip the first line
      if(!file.readLine(list)) return false;

      while(file.readLine(list))
      {
         if(list.size() != 7) {resize(0); return false;}

         bool ok = false;

         double open = list.at(1).toDouble(&ok); if(!ok) {resize(0); return false;}
         double high = list.at(2).toDouble(&ok); if(!ok) {resize(0); return false;}
         double low = list.at(3).toDouble(&ok); if(!ok) {resize(0); return false;}
         double close = list.at(4).toDouble(&ok); if(!ok) {resize(0); return false;}
         double volume = list.at(5).toDouble(&ok); if(!ok) {resize(0); return false;}
         double adjClose = list.at(6).toDouble(&ok); if(!ok) {resize(0); return false;}

         QDate dt = QDate::fromString(list.at(0), "yyyy-MM-dd");

         if(start != NULL && *start > dt) break;

         if (close != adjClose)
         {
            double d = adjClose / close;
            open = round(d * open);
            high = round(d * high);
            low = round(d * low);
            close = round(adjClose);
            volume = round(d * volume);
         }

         append(dt, open, high, low, close, volume);
      }

      reverse();
      result = true;
   }
   else
   {
      result = false;
   }

   return result;
}

bool
Ohlc::storeToYahooCsv(const QString &path)
{
   CsvFile file(path);

   if(file.open(QFile::WriteOnly | QFile::Truncate))
   {
      // output the header
      if(!file.writeLine("Date,Open,High,Low,Close,Volume,Adj Close")) return false;

      for(int i = latest(); i >= first(); --i)
      {
         QStringList fields;
         fields.append(d[i].toString("yyyy-MM-dd"));
         fields.append(QString::number(o[i], 'f', 2));
         fields.append(QString::number(h[i], 'f', 2));
         fields.append(QString::number(l[i], 'f', 2));
         fields.append(QString::number(c[i], 'f', 2));
         fields.append(QString::number(v[i]));
         fields.append(QString::number(c[i], 'f', 2));
         if(!file.writeLine(fields)) return false;
      }
      file.close();
   }
   else
   {
      return false;
   }
   return true;
}

int
Ohlc::dateToIndex(const QDate &date)
{
   for(int i = last(); i >= 0; --i)
   {
      if(d[i] == date) return i;
   }

   return -1;
}

void
Ohlc::reverse()
{
   if(size() <= 1) return;

   int i = first();
   int j = last();
   while(i < j)
   {
      qSwap(d[i], d[j]);
      qSwap(o[i], o[j]);
      qSwap(h[i], h[j]);
      qSwap(l[i], l[j]);
      qSwap(c[i], c[j]);
      qSwap(v[i], v[j]);

      ++i; --j;
   }
}